#include "GeneralThread.h"

jthread::JMutex  GeneralThread::threadmutex;
extern int  g_ThreadIndex;

GeneralThread::GeneralThread(SOCKET sock,char *pIP)
{
	m_sock = sock;
	stop = false;
	memset(m_szIP,0,sizeof(m_szIP));
	strcpy(m_szIP,pIP);
	//m_Range = false;
	//m_pThread = JThreadFunc;
}

GeneralThread::~GeneralThread(void)
{
	if(m_sock)
		::closesocket(m_sock);
	g_ThreadIndex--;
	//printf("~GeneralThread:%d\n",g_ThreadIndex);
}

void *GeneralThread::Thread()
{
    this->ThreadStarted();
	return CHttpSer::pHttp->JThreadFunc(this);
	return (void*)true;
}
int GeneralThread::Start()
{
	if (JThread::IsRunning())
		return -1;
	if (!threadmutex.IsInitialized())
	{
		if (threadmutex.Init() < 0)
			return -2;
	}
	stop = false;
	if (JThread::Start() < 0)
		return -3;

	return 0;

}
void GeneralThread::Stop()
{	
	if (!IsRunning())
		return;
	
	threadmutex.Lock();
	stop = true;
	threadmutex.Unlock();
	
	//bool done = false;

	if (JThread::IsRunning())
	{
		printf("GeneralThread::Stop: Warning! Having to kill thread!\n");
		JThread::Kill();
	}

	//stop = true;
}